import React, { Component } from 'react'
import { connect } from 'dva'
import { Modal, Collapse, Button, Form, Input, List, Spin, Empty, Row, Col, Upload, Icon, message } from 'antd'
import styles from './css/style.css'
import ModalUser from './UserModal.js'
import InfiniteScroll from 'react-infinite-scroller'
import moment from 'moment'

const { TextArea } = Input;
const { Panel } = Collapse;
const formItemLayout = {
    labelCol: { span: 3 },
    wrapperCol: { span: 20 },
};
@Form.create()
class OrderModal extends Component {
    constructor(props) {
        super(props);
        this.state = {
            showType: false,
            previewVisible: false,
            previewImage: '',
            fileList: []
        }
    }

    handleCancel = () => {
        this.setState({
            previewVisible: false
        })
    };

    handlePreview = () => {
        // if (!file.url && !file.preview) {
        //     file.preview = await getBase64(file.originFileObj);
        // }
        // this.setState({
        //     previewImage: file.url || file.preview,
        //     previewVisible: true,
        // });
    };

    handleChange = ({ fileList }) => {
        this.setState({
            fileList
        })
    };

    render() {
        const { visible, order: { orderStatus, is_same_user, orderInfo, warnInfo },
            workflowPic, dispatchUser, dispatchOrder, userModalOpen, acceptTask,
            form: { getFieldDecorator }, cancel, data, loadMore, upload, cancelAlarm } = this.props;
        const showUserModal = () => {
            userModalOpen()
        }
        const send = () => {
            const params = {
                description: this.props.form.getFieldValue('description')
            }
            dispatchOrder(params)
        }
        const handleAccept = (params) => {
            acceptTask({ task_status: params, task_id: orderInfo.task_id })
        }
        const cancelWarn = () => {
            const params = {
                device_id : warnInfo.device_id
            }
            cancelAlarm(params)
        }
        const handleSubmit = (e) => {
            e.preventDefault();
            const fields = this.props.form.getFieldsValue()
            if(fields.info == '') {
                message.warning('请添加处理结果信息！')
                return;
            } else if(fields.files.fileList.length == 0) {
                message.warning('请上传图片！')
                return;
            }
            this.props.form.validateFields(['info', 'files'], (err, fieldsValue) => {
                if(fieldsValue.files && fieldsValue.info) {
                    if (!err) {
                        const params = {
                            ...fieldsValue,
                            taskId: orderInfo.task_id
                        }
                        upload(params)
                    }
                } else {
                    message.warning('请上传图片以及添加处理结果信息！')
                }
            })
        }
        const uploadButton = (
            <div>
                <Icon type="plus" />
                <div className="ant-upload-text"></div>
            </div>
        );
        const handleFormValidated = (rule, value, callback) => {
            if(value.file.type != 'image/png' && value.file.type != 'image/jpeg' && value.file.type != 'image/jpg') {
                callback('请上传png/jpeg/jpg格式图片！')
            }
            callback()
        }

        const picDownload = (file) => {
            console.log(file)
        }

        const beforeUpload = () => {
            return false;
        }
        const { previewVisible, previewImage, fileList } = this.state;
        const renderOrder = () => {
            let returnDom;
            if (!orderInfo.task_id) {
                returnDom = (
                    <Panel key="2" header="工单信息">
                        <Form>
                            <Form.Item label="指派给" {...formItemLayout}>
                                {getFieldDecorator('user_name', {
                                    initialValue: dispatchUser && dispatchUser.user_name ? dispatchUser.user_name : ''
                                })(
                                    <Input style={{ width: '200px', marginRight: '10px' }} />
                                )}
                                <Button type="default" onClick={showUserModal}>+</Button>
                            </Form.Item>
                            <Form.Item label="任务描述" {...formItemLayout}>
                                {getFieldDecorator('description')(
                                    <TextArea row={3} style={{ width: '300px' }} />
                                )}
                            </Form.Item>
                        </Form>
                        <Row>
                            <Col sm={24} xl={24} lg={24} align="right">
                                <Button type="danger" size="small" onClick={cancelWarn}>消警</Button>
                                <Button type="primary" size="small" style={{ margin: '0 10px' }} onClick={send}>指派</Button>
                            </Col>
                        </Row>
                    </Panel>
                )
            } else {
                if (is_same_user) {
                    if (orderInfo.task_name == '处理告警设备') {
                        returnDom = (
                            <Panel header="工单信息" key="2">
                                <Form>
                                    <Form.Item label="处理结果" {...formItemLayout} required>
                                        {
                                            getFieldDecorator('files', {
                                                rules: [{
                                                    validator: handleFormValidated
                                                }]
                                            })(
                                                <Upload
                                                    listType="picture-card"
                                                    fileList={fileList}
                                                    onPreview={this.handlePreview}
                                                    onChange={this.handleChange}
                                                    name="file"
                                                    onDownload={picDownload}
                                                    beforeUpload={beforeUpload}
                                                    // accept='.png,.jpg,.jpeg'
                                                >
                                                    {fileList.length >= 2 ? null : uploadButton}
                                                </Upload>
                                            )
                                        }
                                        <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel} zIndex="9000">
                                            <img alt="example" style={{ width: '100%' }} src={previewImage} />
                                        </Modal>
                                    </Form.Item>
                                    <Form.Item label="告警处理详情" {...formItemLayout} required>
                                        {getFieldDecorator('info')(
                                            <TextArea row={3} style={{ width: '300px' }} />
                                        )}
                                    </Form.Item>
                                    <Row>
                                        <Col xl={4} xm={4} sm={4} lg={4} align="left">
                                            <Button size="small" type="primary" onClick={handleSubmit}>上传</Button>
                                        </Col>
                                    </Row>
                                </Form>
                            </Panel>
                        )
                    } else {
                        returnDom = (
                            <Panel header="工单信息" key="2">
                                <div className={styles.row}>
                                    <p className={styles.left}>
                                        <label>下派人：</label>
                                        <font>{orderInfo.assign_user_name}</font>
                                    </p>
                                    <p className={styles.right}>
                                        <label>下派时间：</label>
                                        <font>{orderInfo.assign_time}</font>
                                    </p>
                                </div>
                                <div className={styles.row}>
                                    <p className={styles.left}>
                                        <label>指派人：</label>
                                        <font>{orderInfo.user_name}</font>
                                    </p>
                                    <p className={styles.right}>
                                        <label>任务描述：</label>
                                        <font>{orderInfo.description}</font>
                                    </p>
                                </div>
                                <Button type="primary" size="small" onClick={() => { handleAccept('1') }}>接受</Button>
                                <Button type="danger" size="small" onClick={() => { handleAccept('-1') }} style={{margin: '0 10px'}}>拒绝</Button>
                            </Panel>
                        )
                    }
                } else {
                    returnDom = (
                        <Panel header="工单信息" key="2">
                            <Empty description={`当前告警已指派给${orderInfo.user_name}`}></Empty>
                        </Panel>
                    )
                }
            }
            return returnDom;
        }
        return (
            <Modal visible={visible} title="工单信息" zIndex="2000" width={1000} onCancel={cancel} footer={null}>
                <Collapse bordered={false} defaultActiveKey={['1', '2']}>
                    {renderOrder()}
                    <div className={styles.row}>
                        <div className={styles.left}>
                            <Collapse bordered={false} defaultActiveKey={['1']}>
                                <Panel header="动态记录" key="1">
                                    <div className={styles.demoInfinite}>
                                        <List
                                            dataSource={data}
                                            renderItem={item => (
                                                <List.Item key={item.TASK_LOG_ID}>
                                                    <List.Item.Meta
                                                        title={<font>当前处理状态：{item.TASK_STATUS}</font>}
                                                    />
                                                    <div>{moment(item.CREATE_TIME).format('YYYY-MM-DD HH:mm:ss')}</div>
                                                </List.Item>
                                            )}
                                        />
                                    </div>
                                </Panel>
                            </Collapse>
                        </div>
                        <div className={styles.right}>
                            <Collapse bordered={false} defaultActiveKey={['1']}>
                                <Panel header="流程图" key="1">
                                    <img src={workflowPic && workflowPic.return_code == 'SUCCESS' ? workflowPic.base64 : null} style={{ width: '100%', height: '100%', margin: '62.5px 0' }} />
                                </Panel>
                            </Collapse>
                        </div>
                    </div>
                </Collapse>
            </Modal>
        )
    }
}

export default OrderModal;
